package protocol

import (
	"encoding/asn1"
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
	"time"
)

// IEC61850Server 实现IEC 61850服务器
type IEC61850Server struct {
	ln             net.Listener
	logicalDevices map[string]*LogicalDevice
	recording      *RecordingInfo // 新增录播信息字段
}

// NewIEC61850Server 创建新的IEC 61850服务器
func NewIEC61850Server() *IEC61850Server {
	return &IEC61850Server{
		logicalDevices: make(map[string]*LogicalDevice),
	}
}

// AddLogicalDevice adds a logical device to the server
func (s *IEC61850Server) AddLogicalDevice(device *LogicalDevice) {
	s.logicalDevices[device.name] = device
}

// GetLogicalNode retrieves a logical node by name
func (s *IEC61850Server) GetLogicalNode(nodeName string) (*LogicalNode, error) {
	for _, device := range s.logicalDevices {
		for _, node := range device.logicalNodes {
			if node.name == nodeName {
				return node, nil
			}
		}
	}
	return nil, fmt.Errorf("logical node not found")
}

// Start 启动服务器
func (s *IEC61850Server) Start(addr string) error {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	s.ln = ln

	go s.acceptConnections()

	return nil
}

// acceptConnections 接受客户端连接
func (s *IEC61850Server) acceptConnections() {
	for {
		conn, err := s.ln.Accept()
		if err != nil {
			continue
		}
		go s.handleConnection(conn)
	}
}

// handleConnection 处理客户端连接
func (s *IEC61850Server) handleConnection(conn net.Conn) {
	defer conn.Close()

	// 处理IEC 61850协议消息
	for {
		buf := make([]byte, 1024)
		n, err := conn.Read(buf)
		if err != nil {
			return
		}

		// 解析IEC 61850消息
		msg := parseMessage(buf[:n])

		// 处理消息
		response := s.handleMessage(msg)

		// 发送响应
		conn.Write(response)
	}
}

// parseMessage 解析IEC 61850消息
func parseMessage(data []byte) *IEC61850Message {
	// 实现消息解析逻辑
	return &IEC61850Message{}
}

// handleMessage 处理IEC 61850消息
func (s *IEC61850Server) handleMessage(msg *IEC61850Message) []byte {
	var response IEC61850Message

	switch msg.Type {
	case "MMSRead":
		readReq, ok := msg.Payload.(MMSReadRequest)
		if !ok {
			response = IEC61850Message{Type: "Error", Payload: "Invalid MMS read request"}
			break
		}

		node, err := s.GetLogicalNode(readReq.NodeName)
		if err != nil {
			response = IEC61850Message{Type: "Error", Payload: err.Error()}
			break
		}

		value := node.GetDataObjects()[readReq.NodeName]
		response = IEC61850Message{Type: "MMSReadResponse", Payload: MMSReadResponse{Value: value}}

	case "MMSWrite":
		writeReq, ok := msg.Payload.(MMSWriteRequest)
		if !ok {
			response = IEC61850Message{Type: "Error", Payload: "Invalid MMS write request"}
			break
		}

		node, err := s.GetLogicalNode(writeReq.NodeName)
		if err != nil {
			response = IEC61850Message{Type: "Error", Payload: err.Error()}
			break
		}

		if err := node.SetDataObject(writeReq.NodeName, writeReq.Value); err != nil {
			response = IEC61850Message{Type: "Error", Payload: err.Error()}
			break
		}

		response = IEC61850Message{Type: "MMSWriteResponse", Payload: MMSWriteResponse{Success: true}}

	default:
		response = IEC61850Message{Type: "Error", Payload: "Unsupported message type"}
	}

	data, _ := json.Marshal(response)
	return data
}

// IEC61850Message 表示IEC 61850消息
type IEC61850Message struct {
	Type    string
	Payload interface{}
}

// IEC61850Client 实现IEC 61850客户端
type IEC61850Client struct {
	conn net.Conn
}

// NewIEC61850Client 创建新的IEC 61850客户端
func NewIEC61850Client() *IEC61850Client {
	return &IEC61850Client{}
}

// Connect 连接到服务器
func (c *IEC61850Client) Connect(addr string) error {
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		return err
	}
	c.conn = conn
	return nil
}

// SendMessage sends an IEC 61850 message
func (c *IEC61850Client) SendMessage(msg *IEC61850Message) error {
	// Encode message as JSON
	data, err := json.Marshal(msg)
	if err != nil {
		return fmt.Errorf("failed to marshal message: %v", err)
	}

	// Send message length first
	length := uint32(len(data))
	if err := binary.Write(c.conn, binary.BigEndian, length); err != nil {
		return fmt.Errorf("failed to send message length: %v", err)
	}

	// Send message data
	if _, err := c.conn.Write(data); err != nil {
		return fmt.Errorf("failed to send message data: %v", err)
	}

	return nil
}

// ReceiveMessage receives an IEC 61850 message
func (c *IEC61850Client) ReceiveMessage() (*IEC61850Message, error) {
	// Read message length
	var length uint32
	if err := binary.Read(c.conn, binary.BigEndian, &length); err != nil {
		return nil, fmt.Errorf("failed to read message length: %v", err)
	}

	// Read message data
	data := make([]byte, length)
	if _, err := io.ReadFull(c.conn, data); err != nil {
		return nil, fmt.Errorf("failed to read message data: %v", err)
	}

	// Decode message from JSON
	var msg IEC61850Message
	if err := json.Unmarshal(data, &msg); err != nil {
		return nil, fmt.Errorf("failed to unmarshal message: %v", err)
	}

	return &msg, nil
}

// LogicalDevice represents a logical device in IEC 61850
type LogicalDevice struct {
	name         string
	logicalNodes []*LogicalNode
}

// NewLogicalDevice creates a new logical device
func NewLogicalDevice(name string) *LogicalDevice {
	return &LogicalDevice{
		name:         name,
		logicalNodes: make([]*LogicalNode, 0),
	}
}

// AddLogicalNode adds a logical node to the device
func (d *LogicalDevice) AddLogicalNode(node *LogicalNode) {
	d.logicalNodes = append(d.logicalNodes, node)
}

// LogicalNode represents a logical node in IEC 61850
type LogicalNode struct {
	name        string
	dataObjects map[string]interface{}
}

// NewLogicalNode creates a new logical node
func NewLogicalNode(name string) *LogicalNode {
	return &LogicalNode{
		name:        name,
		dataObjects: make(map[string]interface{}),
	}
}

// AddDataObject adds a data object to the logical node
func (n *LogicalNode) AddDataObject(name string, type_ int, value interface{}) {
	n.dataObjects[name] = value
}

// Add SetDataObject method to LogicalNode
func (n *LogicalNode) SetDataObject(name string, value interface{}) error {
	if _, exists := n.dataObjects[name]; !exists {
		return fmt.Errorf("data object %s not found", name)
	}
	n.dataObjects[name] = value
	return nil
}

// Add GetDataObjects method to LogicalNode
func (n *LogicalNode) GetDataObjects() map[string]interface{} {
	return n.dataObjects
}

// Add constants for data types
const (
	MX = iota // Measured value
	ST        // Status
)

// Add GetLogicalNode method to IEC61850Client
// GetLogicalNode retrieves a logical node by name
func (c *IEC61850Client) GetLogicalNode(nodeName string) (*LogicalNode, error) {
	// Send request to server to get logical node
	msg := &IEC61850Message{
		Type:    "GetLogicalNode",
		Payload: nodeName,
	}

	if err := c.SendMessage(msg); err != nil {
		return nil, fmt.Errorf("failed to send message: %v", err)
	}

	// Receive response from server
	resp, err := c.ReceiveMessage()
	if err != nil {
		return nil, fmt.Errorf("failed to receive message: %v", err)
	}

	if resp.Type == "Error" {
		return nil, fmt.Errorf("server error: %s", resp.Payload)
	}

	// Parse and return the logical node
	node := &LogicalNode{
		name:        nodeName,
		dataObjects: resp.Payload.(map[string]interface{}),
	}

	return node, nil
}

// MMSReadRequest represents an MMS read request
type MMSReadRequest struct {
	NodeName string
}

// MMSReadResponse represents an MMS read response
type MMSReadResponse struct {
	Value interface{}
}

// MMSWriteRequest represents an MMS write request
type MMSWriteRequest struct {
	NodeName string
	Value    interface{}
}

// MMSWriteResponse represents an MMS write response
type MMSWriteResponse struct {
	Success bool
}

// MMSRead reads a value from a logical node
func (c *IEC61850Client) MMSRead(nodeName string) (interface{}, error) {
	msg := &IEC61850Message{
		Type:    "MMSRead",
		Payload: MMSReadRequest{NodeName: nodeName},
	}

	if err := c.SendMessage(msg); err != nil {
		return nil, fmt.Errorf("failed to send MMS read request: %v", err)
	}

	resp, err := c.ReceiveMessage()
	if err != nil {
		return nil, fmt.Errorf("failed to receive MMS read response: %v", err)
	}

	if resp.Type == "Error" {
		return nil, fmt.Errorf("server error: %s", resp.Payload)
	}

	readResp, ok := resp.Payload.(MMSReadResponse)
	if !ok {
		return nil, fmt.Errorf("invalid MMS read response")
	}

	return readResp.Value, nil
}

// MMSWrite writes a value to a logical node
func (c *IEC61850Client) MMSWrite(nodeName string, value interface{}) error {
	msg := &IEC61850Message{
		Type:    "MMSWrite",
		Payload: MMSWriteRequest{NodeName: nodeName, Value: value},
	}

	if err := c.SendMessage(msg); err != nil {
		return fmt.Errorf("failed to send MMS write request: %v", err)
	}

	resp, err := c.ReceiveMessage()
	if err != nil {
		return fmt.Errorf("failed to receive MMS write response: %v", err)
	}

	if resp.Type == "Error" {
		return fmt.Errorf("server error: %s", resp.Payload)
	}

	writeResp, ok := resp.Payload.(MMSWriteResponse)
	if !ok || !writeResp.Success {
		return fmt.Errorf("MMS write failed")
	}

	return nil
}

// GOOSEMessage represents a GOOSE message
type GOOSEMessage struct {
	AppID       string
	GoID        string
	DataSet     map[string]interface{}
	Timestamp   int64
	StateNumber uint32
	Alarm       bool // 新增报警标志
	Maintenance bool // 新增检修标志
}

// GOOSESubscriber represents a GOOSE subscriber
type GOOSESubscriber struct {
	conn               net.Conn
	alarmHandler       func(*GOOSEMessage) // 新增报警处理函数
	maintenanceHandler func(*GOOSEMessage) // 新增检修处理函数
}

// NewGOOSESubscriber creates a new GOOSE subscriber
func NewGOOSESubscriber() *GOOSESubscriber {
	return &GOOSESubscriber{}
}

// SetAlarmHandler sets the alarm handler
func (s *GOOSESubscriber) SetAlarmHandler(handler func(*GOOSEMessage)) {
	s.alarmHandler = handler
}

// SetMaintenanceHandler sets the maintenance handler
func (s *GOOSESubscriber) SetMaintenanceHandler(handler func(*GOOSEMessage)) {
	s.maintenanceHandler = handler
}

// Subscribe subscribes to GOOSE messages
func (s *GOOSESubscriber) Subscribe(addr string, handler func(*GOOSEMessage)) error {
	conn, err := net.Dial("udp", addr)
	if err != nil {
		return err
	}
	s.conn = conn

	go s.listen(handler)
	return nil
}

// listen listens for incoming GOOSE messages
func (s *GOOSESubscriber) listen(handler func(*GOOSEMessage)) {
	buf := make([]byte, 1024)
	for {
		n, err := s.conn.Read(buf)
		if err != nil {
			continue
		}

		var msg GOOSEMessage
		if err := json.Unmarshal(buf[:n], &msg); err != nil {
			continue
		}

		// 处理报警消息
		if msg.Alarm && s.alarmHandler != nil {
			s.alarmHandler(&msg)
		}

		// 处理检修消息
		if msg.Maintenance && s.maintenanceHandler != nil {
			s.maintenanceHandler(&msg)
		}

		handler(&msg)
	}
}

// GOOSEPublisher represents a GOOSE publisher
type GOOSEPublisher struct {
	conn net.Conn
}

// NewGOOSEPublisher creates a new GOOSE publisher
func NewGOOSEPublisher() *GOOSEPublisher {
	return &GOOSEPublisher{}
}

// Publish publishes a GOOSE message
func (p *GOOSEPublisher) Publish(addr string, msg *GOOSEMessage) error {
	conn, err := net.Dial("udp", addr)
	if err != nil {
		return err
	}
	p.conn = conn

	data, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	_, err = p.conn.Write(data)
	return err
}

// PublishAlarm publishes a GOOSE alarm message
func (p *GOOSEPublisher) PublishAlarm(addr string, appID string, goID string, alarmData map[string]interface{}) error {
	msg := &GOOSEMessage{
		AppID:     appID,
		GoID:      goID,
		DataSet:   alarmData,
		Timestamp: time.Now().Unix(),
		Alarm:     true,
	}
	return p.Publish(addr, msg)
}

// PublishMaintenance publishes a GOOSE maintenance message
func (p *GOOSEPublisher) PublishMaintenance(addr string, appID string, goID string, maintenanceData map[string]interface{}) error {
	msg := &GOOSEMessage{
		AppID:       appID,
		GoID:        goID,
		DataSet:     maintenanceData,
		Timestamp:   time.Now().Unix(),
		Maintenance: true,
	}
	return p.Publish(addr, msg)
}

// SMVMessage represents an SMV message
type SMVMessage struct {
	AppID      string
	SVID       string
	Samples    []float64
	Timestamp  int64
	SampleRate uint32
	Quality    uint16
}

// SMVSubscriber represents an SMV subscriber
type SMVSubscriber struct {
	conn net.Conn
}

// NewSMVSubscriber creates a new SMV subscriber
func NewSMVSubscriber() *SMVSubscriber {
	return &SMVSubscriber{}
}

// Subscribe subscribes to SMV messages
func (s *SMVSubscriber) Subscribe(addr string, handler func(*SMVMessage)) error {
	conn, err := net.Dial("udp", addr)
	if err != nil {
		return err
	}
	s.conn = conn

	go s.listen(handler)
	return nil
}

// listen listens for incoming SMV messages
func (s *SMVSubscriber) listen(handler func(*SMVMessage)) {
	buf := make([]byte, 1024)
	for {
		n, err := s.conn.Read(buf)
		if err != nil {
			continue
		}

		var msg SMVMessage
		if err := json.Unmarshal(buf[:n], &msg); err != nil {
			continue
		}

		handler(&msg)
	}
}

// SMVPublisher represents an SMV publisher
type SMVPublisher struct {
	conn net.Conn
}

// NewSMVPublisher creates a new SMV publisher
func NewSMVPublisher() *SMVPublisher {
	return &SMVPublisher{}
}

// Publish publishes an SMV message
func (p *SMVPublisher) Publish(addr string, msg *SMVMessage) error {
	conn, err := net.Dial("udp", addr)
	if err != nil {
		return err
	}
	p.conn = conn

	data, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	_, err = p.conn.Write(data)
	return err
}

// ASN1Encode encodes a value using ASN.1
func ASN1Encode(value interface{}) ([]byte, error) {
	data, err := asn1.Marshal(value)
	if err != nil {
		return nil, fmt.Errorf("ASN.1 encoding failed: %v", err)
	}
	return data, nil
}

// ASN1Decode decodes ASN.1 data into a value
func ASN1Decode(data []byte, value interface{}) error {
	rest, err := asn1.Unmarshal(data, value)
	if err != nil {
		return fmt.Errorf("ASN.1 decoding failed: %v", err)
	}
	if len(rest) > 0 {
		return errors.New("ASN.1 decoding: extra data found")
	}
	return nil
}

// MMSASN1Encode encodes an MMS message using ASN.1
func MMSASN1Encode(msg *IEC61850Message) ([]byte, error) {
	data, err := asn1.Marshal(*msg)
	if err != nil {
		return nil, fmt.Errorf("MMS ASN.1 encoding failed: %v", err)
	}
	return data, nil
}

// MMSASN1Decode decodes ASN.1 data into an MMS message
func MMSASN1Decode(data []byte) (*IEC61850Message, error) {
	var msg IEC61850Message
	rest, err := asn1.Unmarshal(data, &msg)
	if err != nil {
		return nil, fmt.Errorf("MMS ASN.1 decoding failed: %v", err)
	}
	if len(rest) > 0 {
		return nil, errors.New("MMS ASN.1 decoding: extra data found")
	}
	return &msg, nil
}

// GOOSEASN1Encode encodes a GOOSE message using ASN.1
func GOOSEASN1Encode(msg *GOOSEMessage) ([]byte, error) {
	data, err := asn1.Marshal(*msg)
	if err != nil {
		return nil, fmt.Errorf("GOOSE ASN.1 encoding failed: %v", err)
	}
	return data, nil
}

// GOOSEASN1Decode decodes ASN.1 data into a GOOSE message
func GOOSEASN1Decode(data []byte) (*GOOSEMessage, error) {
	var msg GOOSEMessage
	rest, err := asn1.Unmarshal(data, &msg)
	if err != nil {
		return nil, fmt.Errorf("GOOSE ASN.1 decoding failed: %v", err)
	}
	if len(rest) > 0 {
		return nil, errors.New("GOOSE ASN.1 decoding: extra data found")
	}
	return &msg, nil
}

// SMVASN1Encode encodes an SMV message using ASN.1
func SMVASN1Encode(msg *SMVMessage) ([]byte, error) {
	data, err := asn1.Marshal(*msg)
	if err != nil {
		return nil, fmt.Errorf("SMV ASN.1 encoding failed: %v", err)
	}
	return data, nil
}

// SMVASN1Decode decodes ASN.1 data into an SMV message
func SMVASN1Decode(data []byte) (*SMVMessage, error) {
	var msg SMVMessage
	rest, err := asn1.Unmarshal(data, &msg)
	if err != nil {
		return nil, fmt.Errorf("SMV ASN.1 decoding failed: %v", err)
	}
	if len(rest) > 0 {
		return nil, errors.New("SMV ASN.1 decoding: extra data found")
	}
	return &msg, nil
}

// MMSReportRequest represents an MMS report request
type MMSReportRequest struct {
	ReportType string // "Signal", "Measurement", "Fault"
	Parameters map[string]interface{}
}

// MMSReportResponse represents an MMS report response
type MMSReportResponse struct {
	Success bool
	Data    interface{}
}

// MMSControlRequest represents an MMS control request
type MMSControlRequest struct {
	ControlType string // "Custom", "Standard"
	Parameters  map[string]interface{}
}

// MMSControlResponse represents an MMS control response
type MMSControlResponse struct {
	Success bool
}

// SignalReport sends a signal report
func (c *IEC61850Client) SignalReport(signals map[string]interface{}) error {
	msg := &IEC61850Message{
		Type: "MMSReport",
		Payload: MMSReportRequest{
			ReportType: "Signal",
			Parameters: signals,
		},
	}

	return c.sendMMSReport(msg)
}

// MeasurementReport sends a measurement report
func (c *IEC61850Client) MeasurementReport(measurements map[string]float64) error {
	// Convert map[string]float64 to map[string]interface{}
	params := make(map[string]interface{})
	for k, v := range measurements {
		params[k] = v
	}

	msg := &IEC61850Message{
		Type: "MMSReport",
		Payload: MMSReportRequest{
			ReportType: "Measurement",
			Parameters: params, // Use the converted map
		},
	}

	return c.sendMMSReport(msg)
}

// FaultReport sends a fault report
func (c *IEC61850Client) FaultReport(faults map[string]string) error {
	// Convert map[string]string to map[string]interface{}
	params := make(map[string]interface{})
	for k, v := range faults {
		params[k] = v
	}

	msg := &IEC61850Message{
		Type: "MMSReport",
		Payload: MMSReportRequest{
			ReportType: "Fault",
			Parameters: params, // Use the converted map
		},
	}

	return c.sendMMSReport(msg)
}

// CustomControl sends a custom control command
func (c *IEC61850Client) CustomControl(params map[string]interface{}) error {
	msg := &IEC61850Message{
		Type: "MMSControl",
		Payload: MMSControlRequest{
			ControlType: "Custom",
			Parameters:  params,
		},
	}

	return c.sendMMSControl(msg)
}

// StandardControl sends a standard control command
func (c *IEC61850Client) StandardControl(params map[string]interface{}) error {
	msg := &IEC61850Message{
		Type: "MMSControl",
		Payload: MMSControlRequest{
			ControlType: "Standard",
			Parameters:  params,
		},
	}

	return c.sendMMSControl(msg)
}

// sendMMSReport sends an MMS report
func (c *IEC61850Client) sendMMSReport(msg *IEC61850Message) error {
	if err := c.SendMessage(msg); err != nil {
		return fmt.Errorf("failed to send MMS report: %v", err)
	}

	resp, err := c.ReceiveMessage()
	if err != nil {
		return fmt.Errorf("failed to receive MMS report response: %v", err)
	}

	if resp.Type == "Error" {
		return fmt.Errorf("server error: %s", resp.Payload)
	}

	reportResp, ok := resp.Payload.(MMSReportResponse)
	if !ok || !reportResp.Success {
		return fmt.Errorf("MMS report failed")
	}

	return nil
}

// sendMMSControl sends an MMS control command
func (c *IEC61850Client) sendMMSControl(msg *IEC61850Message) error {
	if err := c.SendMessage(msg); err != nil {
		return fmt.Errorf("failed to send MMS control: %v", err)
	}

	resp, err := c.ReceiveMessage()
	if err != nil {
		return fmt.Errorf("failed to receive MMS control response: %v", err)
	}

	if resp.Type == "Error" {
		return fmt.Errorf("server error: %s", resp.Payload)
	}

	controlResp, ok := resp.Payload.(MMSControlResponse)
	if !ok || !controlResp.Success {
		return fmt.Errorf("MMS control failed")
	}

	return nil
}

// MSVCB represents a Multicast Sampled Value Control Block
type MSVCB struct {
	AppID      string
	SVID       string
	SampleRate uint32
	Enabled    bool
	Values     map[string]interface{}
}

// NewMSVCB creates a new MSVCB
func NewMSVCB(appID, svID string, sampleRate uint32) *MSVCB {
	return &MSVCB{
		AppID:      appID,
		SVID:       svID,
		SampleRate: sampleRate,
		Enabled:    false,
		Values:     make(map[string]interface{}),
	}
}

// SendMSVMessage sends an SMV message using the MSVCB configuration
func (m *MSVCB) SendMSVMessage(publisher *SMVPublisher, addr string) error {
	if !m.Enabled {
		return fmt.Errorf("MSVCB is not enabled")
	}

	msg := &SMVMessage{
		AppID:      m.AppID,
		SVID:       m.SVID,
		Samples:    m.getSamples(),
		Timestamp:  time.Now().Unix(),
		SampleRate: m.SampleRate,
		Quality:    0x0001, // Default quality
	}

	return publisher.Publish(addr, msg)
}

// GetMSVCBValue gets a value from the MSVCB
func (m *MSVCB) GetMSVCBValue(key string) (interface{}, error) {
	if value, exists := m.Values[key]; exists {
		return value, nil
	}
	return nil, fmt.Errorf("value not found for key: %s", key)
}

// SetMSVCBValue sets a value in the MSVCB
func (m *MSVCB) SetMSVCBValue(key string, value interface{}) {
	m.Values[key] = value
}

// Enable enables the MSVCB
func (m *MSVCB) Enable() {
	m.Enabled = true
}

// Disable disables the MSVCB
func (m *MSVCB) Disable() {
	m.Enabled = false
}

// getSamples converts values to samples
func (m *MSVCB) getSamples() []float64 {
	samples := make([]float64, 0, len(m.Values))
	for _, value := range m.Values {
		if f, ok := value.(float64); ok {
			samples = append(samples, f)
		}
	}
	return samples
}

// RecordingInfo represents recording information
type RecordingInfo struct {
	StartTime   int64
	EndTime     int64
	Duration    int64
	DataPoints  []DataPoint
	Quality     uint16
	Description string
}

// DataPoint represents a single data point in the recording
type DataPoint struct {
	Timestamp int64
	Value     interface{}
	Quality   uint16
}

// StartRecording starts recording data
func (s *IEC61850Server) StartRecording(description string) (*RecordingInfo, error) {
	recording := &RecordingInfo{
		StartTime:   time.Now().Unix(),
		Description: description,
		DataPoints:  make([]DataPoint, 0),
	}

	s.recording = recording
	return recording, nil
}

// StopRecording stops recording data
func (s *IEC61850Server) StopRecording() (*RecordingInfo, error) {
	if s.recording == nil {
		return nil, fmt.Errorf("no active recording")
	}

	s.recording.EndTime = time.Now().Unix()
	s.recording.Duration = s.recording.EndTime - s.recording.StartTime

	recording := s.recording
	s.recording = nil

	return recording, nil
}

// AddDataPoint adds a data point to the current recording
func (s *IEC61850Server) AddDataPoint(value interface{}, quality uint16) error {
	if s.recording == nil {
		return fmt.Errorf("no active recording")
	}

	dataPoint := DataPoint{
		Timestamp: time.Now().Unix(),
		Value:     value,
		Quality:   quality,
	}

	s.recording.DataPoints = append(s.recording.DataPoints, dataPoint)
	return nil
}

// GetRecordingInfo retrieves the current recording information
func (s *IEC61850Server) GetRecordingInfo() (*RecordingInfo, error) {
	if s.recording == nil {
		return nil, fmt.Errorf("no active recording")
	}

	return s.recording, nil
}
